package com.doublethread.easymart.interceptor;

import com.doublethread.easymart.common.context.UserContext;
import com.doublethread.easymart.common.exception.AuthException;
import com.doublethread.easymart.common.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT认证拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 公共API直接放行
        if (isPublicApi(requestURI)) {
            return true;
        }

        // 预检请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 获取Token
        String token = getTokenFromRequest(request);
        if (!StringUtils.hasText(token)) {
            // 未提供Token
            AuthException.missingToken();
        }

        // 验证Token
        if (!jwtUtils.validateToken(token)) {
            // Token无效或过期
            AuthException.unauthorized();
        }

        // 获取用户信息
        Long userId = jwtUtils.getUserIdFromToken(token);
        String username = jwtUtils.getUsernameFromToken(token);

        // 设置用户上下文
        UserContext.setCurrentUser(userId, username);

        // 检查管理员权限
        if (requestURI.startsWith("/api/admin/") && !UserContext.isAdmin()) {
            // 权限不足
            AuthException.forbidden();
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户上下文
        UserContext.clear();
    }

    /**
     * 判断是否为公共API
     */
    private boolean isPublicApi(String requestURI) {
        // 登录注册接口
        if (requestURI.equals("/api/auth/login") || requestURI.equals("/api/auth/register")) {
            return true;
        }

        // 公共接口（所有以/api/public开头的接口）
        if (requestURI.startsWith("/api/public")) {
            return true;
        }

        // 评论接口（公开查看）
        return requestURI.startsWith("/api/comments");
    }

    /**
     * 从请求中获取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
